package com.groupbuying.settleconsumer.service.impl;

import com.groupbuying.settleconsumer.connector.StoreFeign;
import com.groupbuying.settleconsumer.constants.SettleUshopFlowStoreEnumConstants;
import com.groupbuying.settleconsumer.domain.SettleUshopFlowStoreDO;
import com.groupbuying.settleconsumer.service.SettleUshopFlowStoreService;
import com.groupbuying.settleconsumer.utils.apiresult.ApiResult;
import com.groupbuying.settleconsumer.connector.OrderFeign;
import com.groupbuying.settleconsumer.connector.SysconfigFeign;
import com.groupbuying.settleconsumer.constants.SettlePaymentReceiptEnumConstants;
import com.groupbuying.settleconsumer.dto.YSPaymentReturnDTO;
import com.groupbuying.settleconsumer.service.SettleUshopPaymentReceiptService;
import com.groupbuying.settleconsumer.utils.JsonUtils;
import com.groupbuying.settleconsumer.dao.SettleUshopPaymentReceiptDao;
import com.groupbuying.settleconsumer.domain.SettlePaymentReceiptDO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SettleUshopPaymentReceiptServiceImpl implements SettleUshopPaymentReceiptService {
	public static final Logger logger = LoggerFactory.getLogger(OrderSettlementServiceImpl.class);
	@Autowired(required = false)
	private SettleUshopPaymentReceiptDao settleUshopPaymentReceiptDao;
	@Autowired
	private OrderFeign orderFeign;
	@Autowired
	private SysconfigFeign sysconfigFeign;
	@Autowired
	private StoreFeign storeFeign;
	@Autowired
	private SettleUshopFlowStoreService settleUshopFlowStoreService;
	@Override
	public SettlePaymentReceiptDO get(Integer paymentreceiptId){
		return settleUshopPaymentReceiptDao.get(paymentreceiptId);
	}

	@Override
	public List<SettlePaymentReceiptDO> list(Map<String, Object> map){
		return settleUshopPaymentReceiptDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return settleUshopPaymentReceiptDao.count(map);
	}
	
	@Override
	public int save(SettlePaymentReceiptDO settlePaymentReceipt){
		return settleUshopPaymentReceiptDao.save(settlePaymentReceipt);
	}
	
	@Override
	public int update(SettlePaymentReceiptDO settlePaymentReceipt){
		return settleUshopPaymentReceiptDao.update(settlePaymentReceipt);
	}
	
	@Override
	public int remove(Integer paymentreceiptId){
		return settleUshopPaymentReceiptDao.remove(paymentreceiptId);
	}
	
	@Override
	public int batchRemove(Integer[] paymentreceiptIds){
		return settleUshopPaymentReceiptDao.batchRemove(paymentreceiptIds);
	}
	@Override
	@Transactional
	public ApiResult createPaymentReceipt(String paymentreceipt) {
		SettlePaymentReceiptDO settlePaymentReceiptDO = new SettlePaymentReceiptDO();
		/*银盛异步返回信息*/
		YSPaymentReturnDTO ysPaymentReturnDTO = (YSPaymentReturnDTO) JsonUtils.convertBean(paymentreceipt, YSPaymentReturnDTO.class);
		if (ysPaymentReturnDTO != null) {
			/*解析参数*/
			try {
				String accountDate = ysPaymentReturnDTO.getAccount_date();
				String fee = ysPaymentReturnDTO.getFee();
				String notifyTime = ysPaymentReturnDTO.getNotify_time();
				String outTradeNo = ysPaymentReturnDTO.getOut_trade_no();
				String partnerFee = ysPaymentReturnDTO.getPartner_fee();
				String payeeFee = ysPaymentReturnDTO.getPayee_fee();
				String totalAmount = ysPaymentReturnDTO.getTotal_amount();
				String tradeNo = ysPaymentReturnDTO.getTrade_no();
				String tradeStatus = ysPaymentReturnDTO.getTrade_status();
				String tradeStatusDescription = ysPaymentReturnDTO.getTrade_status_description();
				String sign = ysPaymentReturnDTO.getSign();
				String payerFee = ysPaymentReturnDTO.getPayer_fee();
				String signType = ysPaymentReturnDTO.getSign_type();
				String notifyTyp = ysPaymentReturnDTO.getNotify_type();
				if (StringUtils.isNotEmpty(outTradeNo) && StringUtils.isNotEmpty(tradeStatus)&& StringUtils.isNotEmpty(accountDate) && StringUtils.isNotEmpty(totalAmount) && StringUtils.isNotEmpty(partnerFee)
						&& StringUtils.isNotEmpty(payeeFee) && StringUtils.isNotEmpty(payerFee)&&StringUtils.isNotEmpty(notifyTime)&&StringUtils.isNotEmpty(notifyTyp)&&StringUtils.isNotEmpty(sign)&&StringUtils.isNotEmpty(signType)) {
				if(tradeStatusDescription.equalsIgnoreCase(SettlePaymentReceiptEnumConstants.ENUM_TRADE_SUCCESS)){
					//交易成功
					settlePaymentReceiptDO.setAccountDate(accountDate);
					settlePaymentReceiptDO.setFee(new BigDecimal(fee));
					settlePaymentReceiptDO.setNotifyTime(notifyTime);
					settlePaymentReceiptDO.setNotifyType(notifyTyp);
					settlePaymentReceiptDO.setOutTradeNo(outTradeNo);
					settlePaymentReceiptDO.setPartnerFee(new BigDecimal(partnerFee));
					settlePaymentReceiptDO.setPayerFee(new BigDecimal(payerFee));
					settlePaymentReceiptDO.setPayeeFee(new BigDecimal(payeeFee));
					settlePaymentReceiptDO.setSign(sign);
					settlePaymentReceiptDO.setSignType(signType);
					settlePaymentReceiptDO.setTradeStatusDescription(tradeStatusDescription);
					settlePaymentReceiptDO.setTradeStatus(tradeStatus);
					settlePaymentReceiptDO.setTradeNo(tradeNo);
					settlePaymentReceiptDO.setTotalAmount(new BigDecimal(totalAmount));
					settlePaymentReceiptDO.setIsDelete(SettlePaymentReceiptEnumConstants.ENUM_ISDELETE_UNDEL);
					settlePaymentReceiptDO.setGmtCreate(new Date());
					settlePaymentReceiptDO.setGmtModified(new Date());
					this.save(settlePaymentReceiptDO);
					logger.info("SettleUshopPaymentReceiptServiceImpl-->createPaymentReceipt success!");
					return ApiResult.success(ysPaymentReturnDTO);
				}else {
					//打款异常钱返回账户中
					settlePaymentReceiptDO.setAccountDate(accountDate);
					settlePaymentReceiptDO.setFee(new BigDecimal(fee));
					settlePaymentReceiptDO.setNotifyTime(notifyTime);
					settlePaymentReceiptDO.setNotifyType(notifyTyp);
					settlePaymentReceiptDO.setOutTradeNo(outTradeNo);
					settlePaymentReceiptDO.setPartnerFee(new BigDecimal(partnerFee));
					settlePaymentReceiptDO.setPayerFee(new BigDecimal(payerFee));
					settlePaymentReceiptDO.setPayeeFee(new BigDecimal(payeeFee));
					settlePaymentReceiptDO.setSign(sign);
					settlePaymentReceiptDO.setSignType(signType);
					settlePaymentReceiptDO.setTradeStatusDescription(tradeStatusDescription);
					settlePaymentReceiptDO.setTradeStatus(tradeStatus);
					settlePaymentReceiptDO.setTradeNo(tradeNo);
					settlePaymentReceiptDO.setTotalAmount(new BigDecimal(totalAmount));
					settlePaymentReceiptDO.setIsDelete(SettlePaymentReceiptEnumConstants.ENUM_ISDELETE_UNDEL);
					settlePaymentReceiptDO.setGmtCreate(new Date());
					settlePaymentReceiptDO.setGmtModified(new Date());
					this.save(settlePaymentReceiptDO);
					//把对应商户的退款金额退回到原始账户上
					/*插入一条提现记录到分账商户子表中--提现金额为正数*/
					SettleUshopFlowStoreDO settleUshopFlowStoreDO=new SettleUshopFlowStoreDO();
					settleUshopFlowStoreDO.setAmount(new BigDecimal(totalAmount));
					//调用订单中心获取收银台ID
					String counterId= this.orderFeign.getCounterIdByOrderId(outTradeNo);
					settleUshopFlowStoreDO.setStoreId(counterId);
					Map<String,Object> storeParams = new HashMap<>();
					storeParams.put("counterId",counterId);
					storeParams.put("delflag","1");
					logger.error("SettleUshopPaymentReceiptServiceImpl-->createPaymentReceipt storeFeign.getMerchantsId params:::"+JsonUtils.objectToJson(storeParams));
					Map<String,Object> storeResult = storeFeign.getMerchantsId(storeParams);
					logger.error("SettleUshopPaymentReceiptServiceImpl-->createPaymentReceipt storeFeign.getMerchantsId result:::"+JsonUtils.objectToJson(storeResult));
					//获取结算id
					String settleId=sysconfigFeign.getWithdrawalId();
					settleUshopFlowStoreDO.setExternalId(settleId);
					settleUshopFlowStoreDO.setGmtCreate(new Date());
					settleUshopFlowStoreDO.setGmtModified(new Date());
					settleUshopFlowStoreDO.setIsDelete(SettleUshopFlowStoreEnumConstants.ENUM_ISDELETE_UNDEL);
					settleUshopFlowStoreDO.setFlowType(SettleUshopFlowStoreEnumConstants.ENUM_FLOWTYPE_REFUND);
					settleUshopFlowStoreDO.setNote(SettleUshopFlowStoreEnumConstants.ENUM_PAYMENT_FAILURE);
					settleUshopFlowStoreDO.setOperateMan((String) storeResult.get("operateMan"));
					settleUshopFlowStoreDO.setOperateTel((String) storeResult.get("operateTel"));
					this.settleUshopFlowStoreService.save(settleUshopFlowStoreDO);
					logger.info("SettleUshopPaymentReceiptServiceImpl-->createPaymentReceipt failure!------>"+outTradeNo);
					return ApiResult.failure();
				}
				} else {
					return ApiResult.failure(ysPaymentReturnDTO);
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				logger.error("SettleUshopPaymentReceiptServiceImpl-->createPaymentReceipt fail e:",e);
			}
		} else {
			logger.info("SettleUshopPaymentReceiptServiceImpl-->createPaymentReceipt failure!");
			return ApiResult.failure("获取银盛打款异步参数为空!");
		}
		return ApiResult.failure();
	}

}
